import java.nio.ByteBuffer;
import java.nio.LongBuffer;
import java.nio.channels.*;
public class db_file {
	private FileChannel oChannel = null;
	private long lPosition = 0;
	
	db_file(FileChannel oFileChannel) {
		oChannel = oFileChannel;
	}

	public void seek(long lPositionVal) throws Exception{
		lPosition = lPositionVal;
		//System.out.println(Thread.currentThread().getId() + " have seeked to " + lPosition);
	}

	public long readLong() throws Exception{
		synchronized (oChannel) {
			ByteBuffer oData = ByteBuffer.allocate(8);
			LongBuffer oLong = oData.asLongBuffer();
			oData.clear();
			oChannel.position(lPosition);
			oChannel.read(oData);
			lPosition += 8;
			return oLong.get(0);
		}

	}

	public void writeLong(long v) throws Exception{

		synchronized (oChannel) {
			db_bytes oBytes = new db_bytes(8);
			oBytes.write(v);

			ByteBuffer oData = ByteBuffer.allocate(8);

			oData.put(oBytes.getBytes());
			oData.clear();
			oChannel.position(lPosition);
			oChannel.write(oData);
			oChannel.force(false);
			
		}

		lPosition += 8;
	}

	public void write(byte[] bBytes) throws Exception {
		//System.out.println(Thread.currentThread().getId() + " is about to commit a page at position: " + oChannel.position());

		synchronized (oChannel) {
			ByteBuffer oData = ByteBuffer.allocate(bBytes.length);
			oData.put(bBytes);
			oData.clear();
			oChannel.position(lPosition);
			oChannel.write(oData);
			oChannel.force(false);
		}
		lPosition += bBytes.length;
		//System.out.println(Thread.currentThread().getId() + " committed new page " + oChannel.size());
	}
	public long length() throws Exception{
		return oChannel.size();
	}


}
